import flixel.FlxSprite;
import flixel.FlxObject;
import flixel.FlxG;
import flixel.addons.tile.FlxTilemapExt;

class Character extends FlxSprite{
	private static inline var wallJumpVelocityThreshold: Float = 100;
	private static inline var jumpVelocity: Float = 200;
	private var canDoubleJump: Bool;
	private var solidLayer: FlxTilemapExt;

	public function new(x: Float = 0, y: Float = 0, SolidLayer: FlxTilemapExt){
		super(x, y);
		solidLayer = SolidLayer;
		loadGraphic("assets/img/charzera_0.png", true, 25, 45);
		animation.add("idle", [44], 1);
		animation.add("walking", [0, 1, 2, 3, 4, 5, 6, 7], 10);
		animation.add("jumping", [11], 1);
		animation.add("dying", [9], 1);
		drag.x = 200;
		acceleration.y = 300;
		maxVelocity.x = 100;

		// ajusta el AABB
		width = 12;
		height = 40; offset.y = 5;
		canDoubleJump = true;
		animation.play("idle");		
	}

	public override function update(){
		// caso especial, si está muriendo no permitimos mover
		if(animation.curAnim.name == "dying"){
			super.update();
			return;
		}
		
		FlxG.collide(solidLayer, this);
		if(FlxG.keys.pressed.A){
			acceleration.x = -150;
			if (touching & FlxObject.FLOOR != 0)
				animation.play("walking");
			flipX = true;
		}else if(FlxG.keys.pressed.D){
			acceleration.x = 150;
			if (touching & FlxObject.FLOOR != 0)
				animation.play("walking");
			flipX = false;
		}else{
			acceleration.x = 0;
			if (touching & FlxObject.FLOOR != 0)
				animation.play("idle");
		}


		if(FlxG.keys.justPressed.W){
			if((wasTouching & FlxObject.FLOOR != 0)){
				velocity.y = -jumpVelocity;
				canDoubleJump = true;
			}
			/*else{
					if(velocity.y >= 0 && Reg.currentState.hasItem("doublejump") && canDoubleJump){
					velocity.y = -jumpVelocity;
					canDoubleJump = false;
				}
			}*/
		}

		if ((touching & FlxObject.FLOOR) == 0)
			animation.play("jumping");
		

		// ajusta el AABB segun la orientacion
		if (facing == FlxObject.RIGHT)
			offset.x = 6;
		else
			offset.x = 6;
		// el update va luego para que funcione la logica del salto, de lo contrario la lógica de colision ajusta al personaje al piso
		super.update();
		/*if(FlxG.keys.justPressed("S")){
			acceleration.y = 0;
			velocity.y = 0;
		}*/
	}

	public function die()
	{
		velocity.x = acceleration.x = 0;
		velocity.y = -30;
		acceleration.y = 200;
		animation.play("dying");
		allowCollisions = 0;
		//angularVelocity = 60;
	}
}